package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SysDeptEntity;
import com.cari.oa.service.SysDeptService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
* Title: SysDeptController
* Description:部门Controller
* Company: cari 
* @author    hjx 
* @date       2013-1-23
*/
@Controller
@SessionAttributes("username")
public class SysDeptController {

    @Resource
    private SysDeptService sysDeptService;
    
    public static final String MODULE_NAME = "SYS_DEPT_MANAGE";

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @RequestMapping("system/dept/list.do")
    public String list(String deptNo, String deptName, String pNo, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        long totalRecords = sysDeptService.getCount(deptNo, deptName, pNo);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        List<SysDeptEntity> deptList = sysDeptService.getPage(deptNo, deptName, pNo, curPage, Contants.PAGE_SIZE);
        List<String> treeList = sysDeptService.getTree(false);   
        modelMap.addAttribute("deptList", deptList);
        modelMap.addAttribute("treeList", treeList);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("deptNo", deptNo);
        modelMap.addAttribute("deptName", deptName);
        modelMap.addAttribute("pNo", pNo);
        return "system/dept/list";
    }
    
    @RequestMapping(value = "/system/dept/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs, ModelMap modelMap) {
    	List<String> treeList = sysDeptService.getTree(true);      
    	modelMap.addAttribute("treeList", treeList);
        modelMap.addAttribute("qs", qs);
        return "system/dept/insert";
    }
    

    @RequestMapping(value = "/system/dept/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, @Valid SysDeptEntity sysDeptEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        if (sysDeptService.existByDeptNo(sysDeptEntity.getDeptNo()))
            return Utils.errorJsonResp("部门编号已存在");
        if (sysDeptService.existByDeptName(sysDeptEntity.getDeptName()))
            return Utils.errorJsonResp("部门名称已存在");

        sysDeptService.insert(sysDeptEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增部门" + sysDeptEntity.getDeptName());
        return Utils.normalJsonResp();
    }
    

    @RequestMapping(value = "/system/dept/view.do", method = RequestMethod.GET)
    public String enterView(String deptNo, ModelMap modelMap) {
        SysDeptEntity dept = sysDeptService.getByDeptNo(deptNo);
        if(StrUtils.isNotEmpty(dept.getpNo())) {
        	SysDeptEntity pDept = sysDeptService.getByDeptNo(dept.getpNo());
            modelMap.addAttribute("pDeptName", pDept.getDeptName());
        }
        modelMap.addAttribute("dept", dept);
        return "system/dept/view";
    }
    
    @RequestMapping(value = "/system/dept/edit.do", method = RequestMethod.GET)
    public String enterEdit(String deptNo, String qs, ModelMap modelMap) {
       
    	List<String> treeList = sysDeptService.getTree(true);    
        SysDeptEntity dept = sysDeptService.getByDeptNo(deptNo);
    	modelMap.addAttribute("treeList", treeList);
    	modelMap.addAttribute("dept", dept);
        modelMap.addAttribute("qs", qs);
        return "system/dept/edit";
    }
    
    /**
     * 
    * Title: postEdit
    * Description:修改部门
    * @author    hjx 
    * @date       2013-1-22 
    * @param username
    * @param sysDeptEntity
    * @param result
    * @return
     */
    @RequestMapping(value = "/system/dept/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, @Valid SysDeptEntity sysDeptEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        sysDeptService.update(sysDeptEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改模块" + sysDeptEntity.getDeptName());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/dept/delete.do")
    @ResponseBody
    public String postDelete(@ModelAttribute("username") String username, String deptNo) {
    	SysDeptEntity sysDeptEntity = sysDeptService.getByDeptNo(deptNo);
        if(sysDeptEntity == null) return Utils.errorJsonResp("该部门已不存在，请刷新页面");
        List<SysDeptEntity>  childList = sysDeptService.getChildDept(deptNo);
        if(childList != null && childList.size()>0)
        {
        	 StringBuffer sb = new StringBuffer("{ ");
             for(SysDeptEntity child : childList)	
             {
            	 sb.append(child.getDeptName()+" ");
             }
             sb.append("}");
             System.out.println(sb.toString());
        	 return Utils.errorJsonResp("该部门含有子部门 "+sb.toString()+" 需先删除子部门！");
        }
        sysDeptService.delete(sysDeptEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "删除模块" + sysDeptEntity.getDeptName());
        return Utils.normalJsonResp();
    }
}
